import { Injectable, inject } from '@angular/core';
import { ElectronService } from '@/service/electron.service';
import { g } from './global-data';


@Injectable({
    providedIn: 'root'
})
export class DataSaveService {
    electronService = inject(ElectronService);

    delete_unused_data(node: any) {
        delete node.parent;
        delete node.style;
        if (!!node.children) {
            for (const child of node.children) {
                this.delete_unused_data(child);
            }
        }
    }

    save_user_data() {
        const user_data = structuredClone(g.user_data_tree[0]);
        this.delete_unused_data(user_data);

        this.electronService.send('save-user-data', JSON.stringify(user_data));
    }

    save_track_data(track_uuid: string) {
        this.electronService.send(
            'save-track-data', 
            {
                track_uuid: track_uuid,
                track_data: JSON.stringify(g.track_line_points_cache.get(track_uuid)),
            }
        );
    }

    save_snapshot() {
        const snapshot: any = {};

        const user_data = structuredClone(g.user_data_tree[0]);
        this.delete_unused_data(user_data);
        snapshot.user_data = JSON.stringify(user_data)

        const map_config = {
            zoom: g.map_canvas.zoom,
            centre_fpx: g.map_canvas.centre_fpx,
            centre_fpy: g.map_canvas.centre_fpy,
            map_source_list: g.map_source_list,
        }
        snapshot.map_config = JSON.stringify(map_config);

        const visible_track_uuids = []
        for (const track_uuid of g.visible_tracks.keys()) {
            visible_track_uuids.push(track_uuid);
        }
        snapshot.visible_track_uuids = JSON.stringify(visible_track_uuids);

        this.electronService.send('save-snapshot', JSON.stringify(snapshot));
    }

}
